package com.maximus.server.socket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketRunner implements Runnable {
    private static final Logger logger = LogManager.getLogger(SocketRunner.class);

    private Socket socket;

    public SocketRunner(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // 处理接收的客户端Socket通信需求
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {

            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                writer.println(inputLine);
            }

            logger.info("Connection closed by client");
        } catch (IOException e) {
            if (e.getMessage().contains("reset")) {
                logger.info("Client forcibly closed connection");
            } else {
                logger.error("Client handling error: " + e.getMessage());
            }
        } finally {
            try {
                socket.close(); // 确保关闭连接
            } catch (IOException e) {
                logger.error("Socket close error: " + e.getMessage());
            }
        }

    }
}
